<template>
    <div ref="containerRef" class="canvas-container">
        <canvas ref="canvasRef"></canvas>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'

// 元素引用
const containerRef = ref<HTMLElement | null>(null)
const canvasRef = ref<HTMLCanvasElement | null>(null)

// 1. 图片资源定义
// 主背景图
const mainBgImage = new Image()
mainBgImage.src = '/public/images/bgCenter.png' // 替换为你的主背景路径

// 矩形1-3的背景图
const rects1to3Image = new Image()
rects1to3Image.src = '/public/images/d1.png' // 替换为第一组矩形背景

// 矩形4-6的背景图
const rects4to6Image = new Image()
rects4to6Image.src = '/public/images/d1fan.png' // 替换为第二组矩形背景

// 2. SVG绘图数据（修改版）
const SVGIcons = {
    "画板 2.svg": {
        draw(ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number) {
            ctx.save()
            ctx.strokeStyle = "rgba(0,0,0,0)"
            ctx.miterLimit = 4

            const baseWidth = 990 // 原始设计宽度
            const baseHeight = 527 // 原始设计高度
            const scaleX = canvasWidth / baseWidth
            const scaleY = canvasHeight / baseHeight
            const scale = Math.min(scaleX, scaleY)

            ctx.scale(scale, scale)

            // 绘制主背景
            drawBackground(ctx, mainBgImage, 0, 0, 990, 527)

            // 定义矩形区域
            const rectGroups = [
                // 矩形1-3
                {
                    image: rects1to3Image,
                    rects: [
                        { x: 128, y: 30, width: 210, height: 56 },  // 矩形1
                        { x: 69, y: 124, width: 210, height: 56 },   // 矩形6
                        { x: 69, y: 230, width: 210, height: 56 },  // 矩形7
                        { x: 128, y: 318, width: 210, height: 56 }  // 矩形8
                    ]
                },
                // 矩形4-6
                {
                    image: rects4to6Image,
                    rects: [
                        { x: 705, y: 124, width: 210, height: 56 }, // 矩形4
                        { x: 705, y: 230, width: 210, height: 56 },  // 矩形5
                        { x: 635, y: 318, width: 210, height: 56 }, // 矩形2
                        { x: 653, y: 30, width: 210, height: 56 },   // 矩形3
                    ]
                }
            ]

            // 为每组矩形绘制对应的背景
            rectGroups.forEach(group => {
                if (group.image.complete && group.image.naturalHeight !== 0) {
                    group.rects.forEach(rect => {
                        // 绘制矩形背景
                        drawBackground(ctx, group.image, rect.x, rect.y, rect.width, rect.height)

                        // 绘制原始矩形样式（半透明灰色）
                        ctx.save()
                        ctx.globalAlpha = 0
                        ctx.fillStyle = "#CCCCCC"
                        ctx.beginPath()
                        ctx.rect(rect.x, rect.y, rect.width, rect.height)
                        ctx.fill()
                        ctx.restore()
                    })
                }
            })

            // 其他矩形（7-8）保持原样
            // const remainingRects = [
            //     { x: 69, y: 230, width: 210, height: 56 },  // 矩形7
            //     { x: 128, y: 318, width: 210, height: 56 }  // 矩形8
            // ]

            // remainingRects.forEach(rect => {
            //     ctx.save()
            //     ctx.globalAlpha = 0.5
            //     ctx.fillStyle = "#CCCCCC"
            //     ctx.beginPath()
            //     ctx.rect(rect.x, rect.y, rect.width, rect.height)
            //     ctx.fill()
            //     ctx.restore()
            // })
            positionText(ctx, "资产总额", 128, 30, 16, "#ffffff");
            positionNumber(ctx, "908", 128, 30, 20, "#ffffff");
            positionImgOne(ctx, "/public/images/d1-1.png", 128, 30, 30, 25, () => { })
            positionText(ctx, "利润总额", 69, 124, 16, "#ffffff");
            positionNumber(ctx, "1448", 69, 124, 20, "#ffffff");
            positionImgOne(ctx, "/public/images/d1-2.png", 69, 124, 30, 25, () => { })
            positionText(ctx, "营业收入", 69, 230, 16, "#ffffff");
            positionNumber(ctx, "2932", 69, 230, 20, "#ffffff");
            positionImgOne(ctx, "/public/images/d1-3.png", 69, 230, 30, 25, () => { })
            positionText(ctx, "职工人数", 128, 318, 16, "#ffffff");
            positionNumber(ctx, "2136", 128, 318, 20, "#ffffff");
            positionImgOne(ctx, "/public/images/d1-4.png", 128, 318, 30, 25, () => { })

            positionText2(ctx, "所有者权益", 653, 30, 16, "#ffffff");
            positionNumberTwo(ctx, "2078", 653, 30, 20, "#ffffff");
            positionImgTwo(ctx, "/public/images/d1-5.png", 653, 30, 30, 25, () => { })
            positionText2(ctx, "负债总颃", 705, 124, 16, "#ffffff");
            positionNumberTwo(ctx, "1448", 705, 124, 20, "#ffffff");
            positionImgTwo(ctx, "/public/images/d1-6.png", 705, 124, 30, 25, () => { })
            positionText2(ctx, "研发经费", 705, 230, 16, "#ffffff");
            positionNumberTwo(ctx, "1912", 705, 230, 20, "#ffffff");
            positionImgTwo(ctx, "/public/images/d1-7.png", 705, 230, 30, 25, () => { })
            positionText2(ctx, "已交税费", 635, 318, 16, "#ffffff");
            positionNumberTwo(ctx, "2136", 635, 318, 20, "#ffffff");
            positionImgTwo(ctx, "/public/images/d1-8.png", 635, 318, 30, 25, () => { })

            ctx.restore()
        }
    }
}

function positionText(ctx, text, x, y, fontSize, fontColor) {
    ctx.save();
    ctx.font = fontSize + "px bold Arial";
    ctx.fillStyle = fontColor;
    ctx.fillText(text, x + 80, y + 35);
}
function positionNumber(ctx, text, x, y, fontSize, fontColor) {
    ctx.save();
    ctx.font = fontSize + "px bold Arial";
    ctx.fillStyle = fontColor;
    ctx.fillText(text, x + 152, y + 35);
}
function positionNumberTwo(ctx, text, x, y, fontSize, fontColor) {
    ctx.save();
    ctx.font = fontSize + "px bold Arial";
    ctx.fillStyle = fontColor;
    ctx.fillText(text, x + 102, y + 35);
}
function positionText2(ctx, text, x, y, fontSize, fontColor) {
    ctx.save();
    ctx.font = fontSize + "px bold Arial";
    ctx.fillStyle = fontColor;
    ctx.fillText(text, x + 25, y + 35);
}

function positionImgOne(ctx, src, x, y, w, h, callBack = () => { }) {
    const img = document.createElement("img");
    img.src = src;
    img.onload = function () {
        ctx.save();
        ctx.drawImage(img, x + 22, y + 10, w, h);
        callBack();
    }
}
function positionImgTwo(ctx, src, x, y, w, h, callBack = () => { }) {
    const img = document.createElement("img");
    img.src = src;
    img.onload = function () {
        ctx.save();
        ctx.drawImage(img, x + 160, y + 10, w, h);
        callBack();
    }
}

// 3. 辅助函数：绘制图片背景（保持比例填充）
const drawBackground = (
    ctx: CanvasRenderingContext2D,
    img: HTMLImageElement,
    x: number,
    y: number,
    width: number,
    height: number
) => {
    if (!img.complete || img.naturalHeight === 0) return

    const imgRatio = img.naturalWidth / img.naturalHeight
    const rectRatio = width / height

    let drawWidth, drawHeight, offsetX, offsetY

    if (imgRatio > rectRatio) {
        // 图片更宽，按高度适配
        drawHeight = height
        drawWidth = height * imgRatio
        offsetX = x + (width - drawWidth) / 2
        offsetY = y
    } else {
        // 图片更高，按宽度适配
        drawWidth = width
        drawHeight = width / imgRatio
        offsetX = x
        offsetY = y + (height - drawHeight) / 2
    }

    ctx.save()
    ctx.beginPath()
    ctx.rect(x, y, width, height)
    ctx.clip() // 限制绘制区域只在矩形内
    ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight)
    ctx.restore()
}

// 4. 绘制Canvas主函数
const drawCanvas = () => {
    if (!canvasRef.value || !containerRef.value) return

    const canvas = canvasRef.value
    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // 获取容器尺寸
    const container = containerRef.value
    const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect()
    const dpr = window.devicePixelRatio || 1

    // 设置Canvas物理尺寸和显示尺寸
    canvas.width = containerWidth * dpr
    canvas.height = containerHeight * dpr
    canvas.style.width = `${containerWidth}px`
    canvas.style.height = `${containerHeight}px`

    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 应用设备像素比缩放
    ctx.save()
    ctx.scale(dpr, dpr)

    // 绘制内容（SVGIcons内部会处理自己的缩放）
    SVGIcons["画板 2.svg"].draw(ctx, containerWidth, containerHeight)

    ctx.restore()
}

// 5. 调整Canvas大小
const resizeCanvas = () => {
    if (!containerRef.value || !canvasRef.value) return

    const container = containerRef.value
    const canvas = canvasRef.value

    // 获取容器尺寸
    const { width, height } = container.getBoundingClientRect()

    // 设置Canvas尺寸（考虑设备像素比）
    const dpr = window.devicePixelRatio || 1
    canvas.width = width * dpr
    canvas.height = height * dpr
    canvas.style.width = `${width}px`
    canvas.style.height = `${height}px`

    // 缩放Canvas上下文
    const ctx = canvas.getContext('2d')
    if (ctx) {
        ctx.scale(dpr, dpr)
        drawCanvas()
    }
}

// 6. 初始化与清理
onMounted(() => {
    // 监听所有图片加载完成
    const images = [mainBgImage, rects1to3Image, rects4to6Image]
    images.forEach(img => {
        if (!img.complete) {
            img.onload = resizeCanvas
        }
    })

    resizeCanvas()
    window.addEventListener('resize', resizeCanvas)
})

onUnmounted(() => {
    window.removeEventListener('resize', resizeCanvas)
})

// 7. 监听容器尺寸变化
const observer = new ResizeObserver(resizeCanvas)
watch(containerRef, (newVal, oldVal) => {
    if (oldVal) observer.unobserve(oldVal)
    if (newVal) observer.observe(newVal)
}, { immediate: true })
</script>

<style scoped>
.canvas-container {
    width: 100%;
    height: 100%;
    max-width: 100vw;
    /* 限制最大宽度为视口宽度 */
    max-height: 100vh;
    /* 限制最大高度为视口高度 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    position: relative;

}

.canvas-container canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
}
</style>